package com.sjf.JavaNIO.charset;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.*;
import java.util.Set;
import java.util.SortedMap;

/**
 * @author <huangtang>
 * @since 2022/4/16 11:08
 **/
public class CharsetDemo {

    public static void main ( String[] args ) throws Exception {
        //1.获取charset对象
        Charset charset = StandardCharsets.UTF_8;
        //2.获取编码器对象
        CharsetEncoder charsetEncoder = charset.newEncoder ();
        //3.创建缓冲区
        CharBuffer buffer = CharBuffer.allocate (1024);
        buffer.put ("today is 2022.4.16尚硅谷");
        buffer.flip ();
        //4.编码
        ByteBuffer byteBuffer = charsetEncoder.encode (buffer);
        System.out.println ("编码结果：");
        while (byteBuffer.hasRemaining ()) {
            System.out.print (byteBuffer.get ());
        }
        System.out.println ();
        byteBuffer.flip ();
        //5.获取解码器对象
        CharsetDecoder charsetDecoder = charset.newDecoder ();
        CharBuffer charBuffer = charsetDecoder.decode (byteBuffer);
        System.out.println ("解码结果：");
        System.out.println (charBuffer.toString ());

        //使用GBK解码
        Charset gbk = StandardCharsets.ISO_8859_1;
        byteBuffer.flip ();
        CharBuffer charBuffer1 = gbk.decode (byteBuffer);
        System.err.println ("使用其他编码：");
        System.err.println (charBuffer1.toString ());

        //获取Charset所支持的编码
        SortedMap<String, Charset> map = Charset.availableCharsets ();
        Set<String> set = map.keySet ();
        for ( String s : set ) {
            System.out.println (map.get (s));
        }
    }
}
